<?php

namespace app\admin\controller;

use think\Request;

class Index
{
    private $out;

    //入口文件
    public function index()
    {
        origin();//跨域
        //接收数据
        $req = Request::instance();
        //接收头部信息
        $head = $req->header();
        //写入头部请求日志
        Fun::LOG(json_encode($head), 'header:');
        //头部参数校验 提交类型method，版本号copyright，接口组interface
        $key = [
            'copyright' => ['isZero' => 1],
            'interface' => ['isZero' => 1],
        ];
        $em = Fun::will($key, $head);
        if ($em['code'] != '000000') {
            //写入返回日志
            Fun::LOG(json_encode($em), 'response:');
            return json_encode($em);
        }
        //接收BODY原始参数
        $data = json_decode(base64_decode($req->param('param')),'true');

        Fun::LOG($req->param('param'), 'admin_param:');
        Fun::LOG(json_encode($data), 'admin_data:');

        //开始跳转方法
        $this->out = $this->goFun($head['copyright'], $head['interface'], $data);
        //写入返回日志
        Fun::LOG(json_encode($this->out), 'response:');
        //返回数据
        return json($this->out);

    }

    private function goFun($copyright,$interface,$data){
        if(!isset($data['command']) || empty($data['command'])){
            $re = Fun::error('999989');
        }else{

            //验证版本号
            if(!is_dir(dirname(__FILE__).DIRECTORY_SEPARATOR.$copyright)){
                //版本号不存在
                return Fun::error('999990');
            }

            //验证接口组
            $class = __NAMESPACE__.'\\'.$copyright.'\\'.$interface;
            if(!class_exists($class)) {
                //接口组不存在
                return Fun::error('999998');
            }

            //验证方法
            if(!method_exists($class,$data['command']) || !is_callable($class,$data['command'])) {
                //方法不存在
                return Fun::error('999997');
            }
            $re = call_user_func(array(new $class($data),$data['command']));
        }

        return $re;
    }

}
